<script setup>
import {reactive, ref, toRefs} from "vue";
import {getTableRecord} from "@/api/lims/sysManager/table";
import {LimsConfig} from "@/api/lims/common/LimsModel";
import {getDecodeData} from "@/api/lims/sop";

const props = defineProps({
  title: String,
  selection: Boolean,
  source:{
    type:String,
    default: 'table'
  },
  sql: String,
  dbType:{type:String, default:'sqlserver'}
})
const emit = defineEmits(['ok'])
const table = ref()
const height = ref(400)
const columns = ref([])
const data = reactive({
  queryParams: {
    keywords: '',
    pageNum: 1,
    pageSize: 50,
  }
})
const {queryParams} = toRefs(data)
const total = ref(0)
const dataList = ref([])
const currentRow = ref()
const selectedRows = ref()
const query = ref()
const baseSql = ref('')
const queryType = ref('')
const order = ref([])

const handleCurrentChange = (val) => {
  currentRow.value = val
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  console.log('selection is ::', selection)
}

const getTableData = () => {
  let config = new LimsConfig(table.value.tableName)
  config.currentPage = queryParams.value.pageNum
  config.pageSize = queryParams.value.pageSize
  config.filters.logic = 'or'
  columns.value.forEach(column => {
    if (column.isQuery) {
      config.filters.like(column.name, queryParams.value.keywords)
    }
  })
  if (table.value.tableName) {
    getTableRecord(config).then(response => {
      total.value = response.dataTotal
      dataList.value = response.data
    })
  }
}
const getList = () => {
  if (queryType.value === 'table'){
    getTableData()
  }else if (queryType.value === 'sql'){
    getListBySql()
  }
}

const enablePage = ref(false)

const getListBySql = () => {
  let querySql = baseSql.value
  if ( queryParams.value.keywords){
    querySql = querySql + ' and ('
    columns.value.forEach((column, index) => {
      console.log('column is ::', column)
      if (column.isQuery){
        if (index === 0){
          querySql = querySql + column.name + ' like \'%' + queryParams.value.keywords + '%\''
        }else {
          querySql = querySql + ' or ' + column.name + ' like \'%' + queryParams.value.keywords + '%\''
        }
      }
    })
    querySql = querySql + ') '

  }
  let countSql = 'select count(*) as total from (' + querySql + ')' + " as c"
  console.log('the order is ::', order.value)
  if (order.value && order.value.length > 0){
    querySql = querySql + 'order by'
    order.value.forEach(item => {
      querySql = querySql + ' ' + item.field + ' ' + item.dir + ','
    })
    // 去除最后一位
    querySql = querySql.slice(0, -1)
  }
  if (enablePage.value){
    if (order.value && order.value.length > 0){
      querySql =  querySql + ' , ' + columns.value[0].name

    }else {
      querySql = querySql + ' order by ' + columns.value[0].name
    }
    querySql = querySql + ' offset ' + (queryParams.value.pageNum-1) * queryParams.value.pageSize + ' rows '
    querySql = querySql + ' fetch next ' + queryParams.value.pageSize + ' rows only'
  }
  console.log('querySql :', querySql, ' \nbaseSql :', baseSql.value)

  getDecodeData(props.dbType, countSql).then(response => {
    total.value = parseInt(response.data[0].TOTAL)
    console.log('total > 0', total.value > 0)
    console.log(' querySql  is ：：：', querySql)
    getDecodeData(props.dbType, querySql).then(response => {
      dataList.value = response.data
    })
  })


}
const visible = ref(false)
const show = (data) => {
  console.log('tableData is ::', data)
  queryType.value = 'table'
  table.value = data
  columns.value = data.columns
  getList()
  visible.value = true
}

const selectBySql = (querySql, queryColumns, isPage, orderColumns) =>{
  enablePage.value = isPage
  columns.value = queryColumns
  queryType.value = 'sql'
  order.value = orderColumns
  baseSql.value = querySql
  getListBySql(querySql)
  visible.value = true
}

const ok = () => {
  if (props.selection){
    emit("ok", selectedRows.value)
  }else {
    emit("ok", currentRow.value)
  }
  close()
}

const close = () => {
  visible.value = false
  total.value = 0
  dataList.value = []
  data.value = {
    queryParams: {
      keywords: '',
      pageNum: 1,
      pageSize: 50,
    }
  }
}

defineExpose({
  show, selectBySql
})
</script>

<template>
  <el-dialog v-model="visible" width="70%" :title="props.title" destroy-on-close>
    <el-input v-model="queryParams.keywords" placeholder="请输入关键词,点击搜索图标查询" clearable
              @keyup.enter="getList">
      <template #append>
        <el-button icon="Search" @click="getList"></el-button>
      </template>
    </el-input>
    <el-table :data="dataList" :height="height"
              highlight-current-row
              @current-change="handleCurrentChange"
              @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="props.selection" type="selection"></el-table-column>
      <el-table-column label="序号" type="index" width="55"></el-table-column>
      <el-table-column v-for="(column,index) in columns"
                       :label="column.label"
                       :prop="column.name"
      ></el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <template #footer>
      <el-button type="primary" @click="ok">确定</el-button>
      <el-button type="danger" @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>